#include "databasemanager.h"

#include <QSqlError>
#include <QDebug>
#include <QTabWidget>

#include "loginwidget.h"

DatabaseManager::DatabaseManager(QObject *parent) : QObject(parent)
{

}

bool DatabaseManager::connectMysql()
{
    if (QSqlDatabase::contains()) { // 检查默认连接是否已存在
        db = QSqlDatabase::database(); // 获取已存在的连接
    } else {
        db = QSqlDatabase::addDatabase("QMYSQL"); // 添加新连接
        db.setHostName("localhost");
        db.setPort(3306);
        db.setUserName("root");
        db.setPassword("123456");
        db.setDatabaseName("serialport");
    }
    if (!db.open())
    {
        qDebug() << "数据库打开失败" << db.lastError().text();
        return false;
    }
    return true;
}

bool DatabaseManager::login(QString username, QString password)
{
    if (!this->connectMysql())
    {
        return false;
    }
    QSqlQuery query(db);
    query.clear();
    query.prepare("SELECT * FROM users WHERE username = :username AND password = :password");
    query.bindValue(":username", username);
    query.bindValue(":password", password);

    if (query.exec()) {
        while (query.next()) {
            // 处理查询结果
            int id = query.value(0).toInt();
            QString name = query.value(1).toString();
            QString pass = query.value(2).toString();
//            qDebug() << "ID:" << id << "Name:" << name << "Password:" << pass;
            return true;
        }
        qDebug() << "账号或者密码错误";
        return false;
    }
    else {
        qDebug() << "语句执行失败";
        return false;
    }
}
